package com.rede.didiok.common.utils.business;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.rede.didiok.common.utils.RedisUtil;

/**
 * @Author: Rede
 * @DateTime: 2024-05-28 15:08
 * @Description: 订单相关工具类
 */
@Component
public class PayOrderUtil {

    @Resource
    private RedisUtil redisUtil;

    private static final String DATE_FORMAT = "yyyyMMddHHmmss";
    private static final String ORDER_SERIAL_NUMBER = "order_serial_number";
    /**
     * 依赖Redis的原子性，设置数据中的自动递增，有效期到12点
     *
     * @param key
     */
    public String getCode(String key) {
        StringBuilder orderNo = new StringBuilder();
        String format = new SimpleDateFormat(DATE_FORMAT).format(new Date());
        orderNo.append(format);
        Long increment = redisUtil.incrBy(key, 1);
        System.out.println("increment"+increment);
        if (increment > 0) {
            //当数据为0的时候，设置有效期,10秒后过期
            //entityIdCounter.expire(3600, TimeUnit.SECONDS);
            //设置到什么时间过期.例：次日凌晨过期
            Date nextDay = new Date(getNextDay());
            redisUtil.expireAt(key, nextDay);
        }
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 2) {//不足2位补0
            orderNo.append(String.format("%02d", increment));
        } else {
            orderNo.append(incrementStr);
        }

        return orderNo.toString();
    }

    /**
     * 获取次日凌晨的时间戳
     *
     * @return
     */
    public long getNextDay() {
        Calendar c = Calendar.getInstance();
//        c.add(Calendar.DAY_OF_YEAR, 1);

        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        //今天凌晨
        return c.getTimeInMillis() / 1000 * (24 * 60 * 60);
    }
//
//    public static void main(String[] args) {
//        PayOrderUtil payOrderUtil = new PayOrderUtil();
//        long a = System.currentTimeMillis();
//        for (int i = 0; i < 20; i++) {
//            System.out.println(payOrderUtil.getCode("code"));
//        }
//        long b = System.currentTimeMillis();
//        System.out.println("耗时：" + (b - a) / 1000);
//    }

}
